/** @odoo-module **/

import { loadJS } from "@web/core/assets";

/**
 * 检测是否在Android原生APP中
 */
function isAndroidApp() {
    return typeof window.AndroidBarcodeScanner !== 'undefined';
}

/**
 * 调用Odoo方法（使用JSON-RPC）
 */
async function callOdooMethod(model, method, args, kwargs) {
    const url = '/web/dataset/call_kw';
    const data = {
        jsonrpc: '2.0',
        method: 'call',
        params: {
            model: model,
            method: method,
            args: args || [],
            kwargs: kwargs || {}
        },
        id: Math.floor(Math.random() * 1000000)
    };
    
    const response = await fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
    });
    
    if (!response.ok) {
        throw new Error(`HTTP错误: ${response.status}`);
    }
    
    const result = await response.json();
    
    if (result.error) {
        throw new Error(result.error.data?.message || result.error.message || '服务器错误');
    }
    
    return result.result;
}

/**
 * Android原生扫码结果回调
 */
window.handleNativeScanResult = async function(scanData) {
    console.log("Native scan result received:", scanData);
    
    // 显示处理中提示
    if (window.AndroidBarcodeScanner) {
        window.AndroidBarcodeScanner.showToast("正在处理...");
    } else {
        showMobileToast("正在处理...", "info");
    }
    
    try {
        // 验证扫描数据
        console.log("扫描数据:", scanData);
        
        // 尝试解析JSON验证格式
        let jsonData;
        try {
            jsonData = JSON.parse(scanData);
            console.log("解析后的数据:", jsonData);
        } catch (e) {
            throw new Error("二维码数据格式错误，无法解析JSON");
        }
        
        // 验证必填字段
        if (!jsonData.wo_part) {
            throw new Error("二维码数据缺少必填字段：wo_part（零件号）");
        }
        if (!jsonData.wo_line) {
            throw new Error("二维码数据缺少必填字段：wo_line（生产线）");
        }
        if (!jsonData.wo_emp) {
            throw new Error("二维码数据缺少必填字段：wo_emp（员工）");
        }
        if (!jsonData.wo_qty_comp) {
            throw new Error("二维码数据缺少必填字段：wo_qty_comp（完工数量）");
        }
        
        // 直接使用JSON-RPC调用（不依赖ORM服务）
        const result = await callOdooMethod(
            "production.work.order",
            "process_barcode_scan_and_submit",
            [],
            {
                barcode_data: scanData
            }
        );
        
        console.log("Backend result:", result);
        console.log("result.success:", result.success);
        console.log("result.message:", result.message);
        
        // 通知客户端动作界面（如果存在）
        if (window.handleProductionScanComplete) {
            window.handleProductionScanComplete(result);
        }
        
        // 显示结果toast
        if (result && result.success) {
            const message = "✅ " + (result.message || "报工成功");
            console.log("显示成功消息:", message);
            if (window.AndroidBarcodeScanner) {
                window.AndroidBarcodeScanner.showToast(message);
            } else {
                showMobileToast(message, "success", 5000);
            }
        } else {
            const message = "❌ " + (result.message || result.error || "报工失败");
            console.log("显示失败消息:", message);
            if (window.AndroidBarcodeScanner) {
                window.AndroidBarcodeScanner.showToast(message);
            } else {
                showMobileToast(message, "error", 8000);
            }
        }
        
    } catch (error) {
        console.error("Error processing scan result:", error);
        const errorMsg = "❌ 处理失败：" + error.message;
        
        if (window.AndroidBarcodeScanner) {
            window.AndroidBarcodeScanner.showToast(errorMsg);
        } else {
            showMobileToast(errorMsg, "error", 5000);
        }
    }
};

/**
 * 全局函数：直接打开生产工单二维码扫描器
 */
window.openProductionBarcodeScannerDirect = async function(record, orm) {
    console.log("Opening production barcode scanner directly");
    
    // 优先使用Android原生扫码
    if (isAndroidApp()) {
        console.log("Using Android native scanner");
        try {
            window.AndroidBarcodeScanner.scanBarcode();
            // 扫码结果会通过 window.handleNativeScanResult() 回调返回
            return;
        } catch (error) {
            console.error("Android scanner error:", error);
            alert("启动原生扫码失败：" + error.message);
            return;
        }
    }
    
    try {
        // 创建自定义对话框
        const modalHtml = `
            <div class="o_barcode_modal_overlay" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 9999; display: flex; align-items: center; justify-content: center;">
                <div class="o_barcode_modal_dialog" style="background: white; border-radius: 8px; max-width: 800px; width: 90%; max-height: 90vh; overflow: auto; box-shadow: 0 10px 40px rgba(0,0,0,0.3);">
                    <div class="o_barcode_modal_header" style="background: #28a745; color: white; padding: 15px 20px; border-radius: 8px 8px 0 0; display: flex; justify-content: space-between; align-items-center;">
                        <h5 style="margin: 0; font-size: 18px;">
                            <i class="fa fa-qrcode" style="margin-right: 8px;"></i>扫描工单二维码
                        </h5>
                        <button type="button" class="o_barcode_modal_close" style="background: transparent; border: none; color: white; font-size: 24px; cursor: pointer; padding: 0; width: 30px; height: 30px; line-height: 1;">&times;</button>
                    </div>
                    <div class="o_barcode_modal_body" style="padding: 20px;">
                        <div style="background: #d4edda; border: 1px solid #c3e6cb; border-radius: 4px; padding: 15px; margin-bottom: 20px; text-align: center;">
                            <h6 style="color: #155724; margin-bottom: 10px;"><i class="fa fa-info-circle"></i> 使用说明</h6>
                            <p style="margin: 5px 0; color: #155724;">📷 <strong>方式1：</strong> 将二维码对准摄像头进行扫描</p>
                            <p style="margin: 5px 0; color: #155724;">📁 <strong>方式2：</strong> 点击"上传图片"上传二维码图片</p>
                            <hr style="margin: 10px 0; border-color: #c3e6cb;"/>
                            <p style="margin: 5px 0; font-size: 13px; color: #155724;"><strong>二维码数据格式（JSON）：</strong></p>
                            <p style="margin: 5px 0; font-size: 12px; color: #155724; font-family: monospace;">{"wo_part":"18G-827-301C","wo_line":"JLHT","wo_emp":"001","wo_qty_comp":20,"wo_op":"99","wo_bk_date":"2025-11-30"}</p>
                        </div>
                        <div id="barcode_reader_production" style="max-width: 600px; margin: 0 auto;"></div>
                        <div id="scanning_status_production" style="text-align: center; margin-top: 20px;">
                            <div class="spinner-border text-success" role="status" style="width: 3rem; height: 3rem; border-width: 0.3em;">
                                <span style="position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0;">正在初始化扫描器...</span>
                            </div>
                            <p style="margin-top: 15px; color: #6c757d;">正在初始化扫描器...</p>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // 移除已存在的对话框
        const existingModal = document.querySelector('.o_barcode_modal_overlay');
        if (existingModal) {
            existingModal.remove();
        }
        
        // 添加对话框到页面
        document.body.insertAdjacentHTML('beforeend', modalHtml);
        
        // 获取对话框元素
        const modalOverlay = document.querySelector('.o_barcode_modal_overlay');
        const closeButton = modalOverlay.querySelector('.o_barcode_modal_close');
        
        // 关闭按钮事件
        const closeModal = () => {
            if (window.currentProductionScanner) {
                try {
                    if (typeof window.currentProductionScanner.stop === 'function') {
                        window.currentProductionScanner.stop().catch(err => console.error("Error stopping scanner:", err));
                    } else if (typeof window.currentProductionScanner.clear === 'function') {
                        window.currentProductionScanner.clear();
                    }
                } catch (err) {
                    console.error("Error stopping scanner:", err);
                }
                window.currentProductionScanner = null;
            }
            modalOverlay.remove();
        };
        
        closeButton.addEventListener('click', closeModal);
        modalOverlay.addEventListener('click', (e) => {
            if (e.target === modalOverlay) {
                closeModal();
            }
        });
        
        // 加载 html5-qrcode 库并启动扫描
        await loadProductionBarcodeScanner(record, orm, closeModal);
        
    } catch (error) {
        console.error("Error opening barcode scanner:", error);
        alert("打开扫描器时出错：" + error.message);
    }
};

/**
 * 加载生产工单条码扫描器
 */
async function loadProductionBarcodeScanner(record, orm, closeModal) {
    try {
        // 动态加载html5-qrcode库
        if (typeof Html5Qrcode === 'undefined') {
            const script = document.createElement('script');
            script.src = 'https://cdn.jsdelivr.net/npm/html5-qrcode@2.3.8/html5-qrcode.min.js';
            document.head.appendChild(script);
            
            await new Promise((resolve, reject) => {
                script.onload = resolve;
                script.onerror = reject;
            });
        }
        
        // 更新状态
        const statusElement = document.getElementById('scanning_status_production');
        if (statusElement) {
            statusElement.innerHTML = `
                <div class="spinner-border text-success" role="status" style="width: 3rem; height: 3rem; border-width: 0.3em;">
                    <span style="position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0;">正在启动摄像头...</span>
                </div>
                <p style="margin-top: 15px; color: #6c757d;">正在启动摄像头，请稍候...</p>
            `;
        }
        
        // 使用 Html5Qrcode
        const html5QrCode = new Html5Qrcode("barcode_reader_production");
        
        // 获取可用摄像头
        const devices = await Html5Qrcode.getCameras();
        console.log("Available cameras:", devices);
        
        // 选择后置摄像头
        let selectedCameraId = null;
        const backCamera = devices.find(device => 
            device.label.toLowerCase().includes('back') || 
            device.label.toLowerCase().includes('rear') ||
            device.label.toLowerCase().includes('后')
        );
        
        if (backCamera) {
            selectedCameraId = backCamera.id;
        } else if (devices.length > 0) {
            selectedCameraId = devices[devices.length - 1].id;
        }
        
        if (!selectedCameraId) {
            alert("未检测到可用的摄像头");
            closeModal();
            return;
        }
        
        // 配置扫描器（优化性能）
        const config = {
            fps: 20,  // 提高帧率到20fps，提升识别速度
            qrbox: { width: 300, height: 300 },  // 增大扫描框，更容易对准
            aspectRatio: 1.0,
            videoConstraints: {
                facingMode: "environment",  // 强制使用后置摄像头
                advanced: [{ zoom: 2.0 }]   // 启用变焦功能（如果支持）
            },
            experimentalFeatures: {
                useBarCodeDetectorIfSupported: true  // 使用浏览器原生检测器（更快）
            }
        };
        
        // 启动扫描器
        await html5QrCode.start(
            selectedCameraId,
            config,
            (decodedText, decodedResult) => {
                onProductionScanSuccess(decodedText, record, orm, closeModal, html5QrCode);
            },
            (errorMessage) => {
                // 扫描失败回调
            }
        );
        
        // 更新状态为正在扫描
        if (statusElement) {
            statusElement.innerHTML = `
                <div style="text-align: center; margin-top: 20px;">
                    <p style="color: #28a745; font-weight: bold; font-size: 16px;">
                        <i class="fa fa-camera" style="margin-right: 8px;"></i>摄像头已启动，请对准二维码
                    </p>
                    <p style="color: #6c757d; font-size: 14px; margin-top: 10px;">
                        或点击下方按钮上传二维码图片
                    </p>
                    <button onclick="document.getElementById('production_barcode_file_upload').click()" 
                            style="margin-top: 10px; padding: 10px 20px; background: #28a745; color: white; border: none; border-radius: 4px; cursor: pointer;">
                        <i class="fa fa-upload" style="margin-right: 5px;"></i>上传二维码图片
                    </button>
                    <input type="file" id="production_barcode_file_upload" accept="image/*" style="display: none;">
                </div>
            `;
            
            // 添加文件上传事件
            document.getElementById('production_barcode_file_upload').addEventListener('change', async (e) => {
                const file = e.target.files[0];
                if (file) {
                    try {
                        const decodedText = await html5QrCode.scanFile(file, false);
                        onProductionScanSuccess(decodedText, record, orm, closeModal, html5QrCode);
                    } catch (err) {
                        alert("无法识别图片中的二维码，请确保图片清晰且包含有效的二维码");
                    }
                }
            });
        }
        
        // 存储扫描器引用
        window.currentProductionScanner = html5QrCode;
        
    } catch (error) {
        console.error("Error loading barcode scanner:", error);
        if (error.name === 'NotAllowedError') {
            alert("摄像头权限被拒绝，请在浏览器设置中允许访问摄像头");
        } else if (error.name === 'NotFoundError') {
            alert("未检测到摄像头设备");
        } else {
            alert("加载扫描器失败：" + error.message);
        }
        closeModal();
    }
}

/**
 * 扫描成功回调 - 自动创建记录并提交到QAD
 */
async function onProductionScanSuccess(barcodeData, record, orm, closeModal, html5QrCode) {
    console.log("Production scan successful:", barcodeData);
    
    try {
        // 停止扫描器
        try {
            await html5QrCode.stop();
        } catch (stopErr) {
            console.warn("Error stopping scanner:", stopErr);
        }
        
        // 关闭扫描对话框
        closeModal();
        
        // 显示处理中的提示
        showMobileToast("正在处理...", "info");
        
        // 调用后端方法：自动创建记录并提交到QAD
        try {
            const result = await callOdooMethod(
                "production.work.order",
                "process_barcode_scan_and_submit",
                [],
                {
                    barcode_data: barcodeData
                }
            );
            
            console.log("Backend result:", result);
            
            // 通知客户端动作界面（如果存在）
            if (window.handleProductionScanComplete) {
                window.handleProductionScanComplete(result);
            }
            
            // 根据结果显示不同的通知
            if (result.success) {
                // 成功：显示绿色toast
                showMobileToast("✅ " + result.message, "success", 5000);
            } else {
                // 失败：显示红色toast
                showMobileToast("❌ " + result.message, "error", 8000);
            }
            
        } catch (error) {
            console.error("Error calling backend:", error);
            showMobileToast("❌ 系统错误：" + error.message, "error", 5000);
        }
        
    } catch (error) {
        console.error("Error processing barcode:", error);
        closeModal();
        showMobileToast("❌ 处理二维码时出错：" + error.message, "error", 5000);
    }
}

/**
 * 显示移动端Toast通知
 */
function showMobileToast(message, type = "info", duration = 3000) {
    // 移除已存在的toast
    const existingToast = document.querySelector('.o_mobile_toast');
    if (existingToast) {
        existingToast.remove();
    }
    
    // 根据类型设置颜色
    let bgColor, icon;
    switch(type) {
        case 'success':
            bgColor = '#28a745';
            icon = '✅';
            break;
        case 'error':
            bgColor = '#dc3545';
            icon = '❌';
            break;
        case 'warning':
            bgColor = '#ffc107';
            icon = '⚠️';
            break;
        default:
            bgColor = '#17a2b8';
            icon = 'ℹ️';
    }
    
    // 创建toast元素
    const toast = document.createElement('div');
    toast.className = 'o_mobile_toast';
    toast.style.cssText = `
        position: fixed;
        top: 20px;
        left: 50%;
        transform: translateX(-50%);
        background: ${bgColor};
        color: white;
        padding: 15px 25px;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.3);
        z-index: 99999;
        font-size: 16px;
        max-width: 90%;
        text-align: center;
        animation: slideDown 0.3s ease-out;
    `;
    toast.innerHTML = `<div style="white-space: pre-line;">${icon} ${message}</div>`;
    
    // 添加CSS动画
    if (!document.querySelector('#mobile_toast_styles')) {
        const style = document.createElement('style');
        style.id = 'mobile_toast_styles';
        style.textContent = `
            @keyframes slideDown {
                from {
                    opacity: 0;
                    transform: translateX(-50%) translateY(-20px);
                }
                to {
                    opacity: 1;
                    transform: translateX(-50%) translateY(0);
                }
            }
        `;
        document.head.appendChild(style);
    }
    
    // 添加到页面
    document.body.appendChild(toast);
    
    // 自动移除
    setTimeout(() => {
        toast.style.animation = 'slideDown 0.3s ease-out reverse';
        setTimeout(() => {
            toast.remove();
        }, 300);
    }, duration);
}
